package com.siqi.hr.system.custom.service;

import com.siqi.hr.common.utils.Const;
import com.siqi.hr.system.common.enums.OperationEnum;
import com.siqi.hr.system.common.model.filter.QueryDataEntity;
import com.siqi.hr.system.common.sql.SFieldType;
import com.siqi.hr.system.custom.dao.intf.DbStructureDao;
import com.siqi.hr.system.custom.dao.intf.EntityRecordDao;
import com.siqi.hr.system.custom.dao.intf.FieldRecordDao;
import com.siqi.hr.system.custom.dao.intf.SelectBoxDao;
import com.siqi.hr.system.custom.entity.EntityOperation;
import com.siqi.hr.system.custom.entity.EntityRecord;
import com.siqi.hr.system.custom.entity.FieldRecord;
import com.siqi.hr.system.custom.entity.SelectBox;
import com.siqi.hr.system.organization.dao.intf.DeptDao;
import com.siqi.hr.system.organization.dao.intf.RoleDao;
import com.siqi.hr.system.organization.entity.Employee;
import com.siqi.hr.system.organization.entity.FieldControled;
import com.siqi.hr.system.organization.entity.Role;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 实体注册字段service层
 * @author    xiaogq
 * Created by xiaogoingqin on 2016/7/24.
 */
@Component("fieldRecordService")
@Transactional(rollbackFor = { Exception.class },propagation = Propagation.REQUIRED)
public class FieldRecordService {
    private static final Logger logger = Logger.getLogger(FieldRecordService.class);

    @Autowired
    EntityRecordDao entityRecordDao;

    @Autowired
    private DeptDao deptDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private FieldRecordDao fieldRecordDao;

    @Autowired
    private SelectBoxDao selectBoxDao;

    @Autowired
    private DbStructureDao dbStructureDao;

    /**
     * 获取属性(自定义字段列表页面表格列头)
     * @author              xiaogq
     * @return
     */
    public Map<String, Object> queryFieldLayoutListColumns() {
        Map<String, Object> columnMap = new HashMap<String, Object>();
        StringBuffer columns = new StringBuffer();
        columns.append("<th data-field='position' data-checkbox='false'></th>");
        columns.append("<th data-field='operation' data-formatter='showColOperator'>操作</th>");
        columns.append("<th data-field='name' data-visible='false'>属性英文名</th>");
        columns.append("<th data-field='inchinese' data-sortable='true'>属性名</th>");
        columns.append("<th data-field='field_type'>数据类型</th>");
        columns.append("<th data-field='calfield'>计算型字段</th>");
        columns.append("<th data-field='restricter'>枚举控制属性</th>");
        columns.append("<th data-field='enum_share'>枚举共享属性</th>");
        columnMap.put("fields", "");
        columnMap.put("columns", columns);
        return columnMap;
    }

    /**
     * 根据实体id以及是否是系统属性标识查询字段注册信息
     * @author              xiaogq
     * @param queryData    分页数据信息
     * @param sysField     系统属性标识(true:系统属性,false:自定义属性)
     * @return
     */
    public Map<String, Object> queryEntityData(QueryDataEntity queryData, Boolean sysField) throws Exception{
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String,Object>> resultDatas = new ArrayList<Map<String,Object>>();
        //根据实体id以及是否是系统属性标识查询字段注册信息
        List<Map<String, Object>> entitysData = fieldRecordDao.getFieldRecords(queryData,sysField);
        int totalCounts = fieldRecordDao.getCountFieldRecords(queryData.getTableCode(),sysField);
        //根据实体id查询当前实体所有注册字段的id、name(英文名)、inchinese(中文名)
        Map<Integer, FieldRecord> fInfoMap = getFieldLocalInfo(queryData.getTableCode());

        for (int i = 0; i < entitysData.size(); i++) {
            Map<String, Object> map = entitysData.get(i);
            List<EntityOperation> optionList = new ArrayList<EntityOperation>();
            //所有实体默认都有编辑按钮
            EntityOperation editField = new EntityOperation("编辑","editField","FieldRecord/fieldRecordEditInit.do","glyphicon glyphicon-edit", OperationEnum.showColumn.name(),new EntityRecord(0));
            optionList.add(editField);
            //得到是否是系统字段标识
            Object system_entity = map.get("sys_field");
            //如果是自定义字段
            if (system_entity == null || !Boolean.parseBoolean(system_entity.toString())) {
                EntityOperation deleteField = new EntityOperation("删除","deleteField","FieldRecord/fieldRecordDelete.do","glyphicon glyphicon-trash",OperationEnum.showColumn.name(),new EntityRecord(0));
                optionList.add(deleteField);
            }
            //如果是属性级控制属性
            if (map.get("controled") != null && (Boolean.parseBoolean(map.get("controled").toString()))) {
                EntityOperation controlField = new EntityOperation("属性级控制","fieldControl","FieldRecord/fieldControlList.do","glyphicon glyphicon-sound-dolby",OperationEnum.showColumn.name(),new EntityRecord(0));
                optionList.add(controlField);
            }

            String fieldName = map.get("name") == null ? "" : map.get("name").toString();
            //定义字段类型长度描述
            String fieldTypeStr = null;

            if (fieldName.equals("name") || fieldName.equals("id")) {
                fieldTypeStr = "文本";
                if (map.get("length") != null)
                    fieldTypeStr = fieldTypeStr + "("+ map.get("length") + ")";
            } else if (fieldName.startsWith("pk_")) {
                fieldTypeStr = "引用";
                String tc = fieldName.split("_")[2];
                try {
                    int tableCode = Integer.parseInt(tc);
                    EntityRecord er = this.entityRecordDao.queryEntityRecordById(tableCode);
                    fieldTypeStr = fieldTypeStr + "("+ er.getInchinese() + ")";
                } catch (NumberFormatException e) {
                }
            } else if (fieldName.endsWith("_radio")) {
                fieldTypeStr = "单选框";
            } else if (fieldName.endsWith("_decimal")) {
                fieldTypeStr = "数值";
                if (map.get("length") != null)
                    fieldTypeStr = fieldTypeStr + "("+ map.get("length") + "."+ map.get("precisions") + ")";
            } else if (fieldName.endsWith("_varchar")) {
                fieldTypeStr = "文本";
                if (map.get("length") != null){
                    fieldTypeStr = fieldTypeStr + "("+ map.get("length") + ")";
                }
            }else if(fieldName.endsWith("_idcard")){
                fieldTypeStr = "身份证号";
                if (map.get("length") != null){
                    fieldTypeStr = fieldTypeStr + "("+ map.get("length") + ")";
                }
            }else if(fieldName.endsWith("_bankcard")){
                fieldTypeStr = "银行卡号";
                if (map.get("length") != null){
                    fieldTypeStr = fieldTypeStr + "("+ map.get("length") + ")";
                }
            } else if (fieldName.endsWith("_datetime")) {
                fieldTypeStr = "日期时间";
            } else if (fieldName.endsWith("_timestamp")) {
                fieldTypeStr = "日期时间";
            } else if (fieldName.endsWith("_date")) {
                fieldTypeStr = "日期";
            } else if (fieldName.endsWith("_bit")) {
                if (fieldName.equals("donotcall_bit") || fieldName.equals("fax_optout_bit") || fieldName.equals("email_optout_bit") || fieldName.equals("emailoptout_bit")){
                    fieldTypeStr = "复选框(批量更新)";
                }else{
                    fieldTypeStr = "复选框";
                }
            } else if (fieldName.endsWith("_phone")) {
                fieldTypeStr = "电话";
            } else if (fieldName.endsWith("_precent")) {
                fieldTypeStr = "百分比";
                if (map.get("length") != null)
                    fieldTypeStr = fieldTypeStr + "("+ map.get("length") + "."+ map.get("precisions") + ")";
            } else if (fieldName.endsWith("_currency")) {
                fieldTypeStr = "货币";
                if (map.get("length") != null)
                    fieldTypeStr = fieldTypeStr + "("+ map.get("length") + "."+ map.get("precisions") + ")";
            } else if (fieldName.endsWith("_email")) {
                fieldTypeStr = "电子邮件";
            } else if (fieldName.endsWith("_web")) {
                fieldTypeStr = "网页";
            } else if (fieldName.endsWith("_singlebox")) {
                fieldTypeStr = "下拉框";
            } else if (fieldName.endsWith("_mutibox")) {
                fieldTypeStr = "下拉框（多选）";
            } else if (fieldName.endsWith("_autosno")) {
                fieldTypeStr = "自动编号";
            } else if (fieldName.endsWith("_textblock")) {
                fieldTypeStr = "文本区域（长）";
            } else if (fieldName.endsWith("_textarea")) {
                fieldTypeStr = "文本区域";
            } else if (fieldName.endsWith("_img")) {
                fieldTypeStr = "图片";
            } else if (fieldName.endsWith("_fastival")) {
                fieldTypeStr = "节日";
            } else if (fieldName.endsWith("_text")) {
                fieldTypeStr = "长文本";
            } else if (fieldName.endsWith("_link")) {
                fieldTypeStr = "链接";
            } else if (fieldName.endsWith("_int")) {
                fieldTypeStr = "数值";
            } else if (fieldName.endsWith("_object")) {
                fieldTypeStr = "引用（引用对象）";
            } else if (fieldName.endsWith("_entity")) {
                fieldTypeStr = "下拉框";
            }
            //如果是必填字段
            if (map.get("nulldisable") != null && (Boolean.parseBoolean(map.get("nulldisable").toString()))) {
                fieldTypeStr = fieldTypeStr + "(必填)";
            }
            if (map.get("value_unique") != null && (Boolean.parseBoolean(map.get("value_unique").toString()))) {
                fieldTypeStr = fieldTypeStr + "(取值唯一)";
            }

            map.put("field_type", fieldTypeStr);
            //如果是单选字段类型
            if (fieldName.endsWith("_radio")) {
                if (map.get("share_field_id") == null){
                    EntityOperation radioField = new EntityOperation("枚举:单选","addSinglebox","FieldRecord/fieldSelectBoxlist.do","glyphicon glyphicon-stats",OperationEnum.showColumn.name(),new EntityRecord(0));
                    optionList.add(radioField);
                }
            }
            //如果是单下拉类型字段
            if (fieldName.indexOf("_singlebox") != -1) {
                if (map.get("share_field_id") == null) {
                    EntityOperation radioField = new EntityOperation("枚举:下拉框","addSinglebox","FieldRecord/fieldSelectBoxlist.do","glyphicon glyphicon-stats",OperationEnum.showColumn.name(),new EntityRecord(0));
                    optionList.add(radioField);
                }
                EntityOperation radioField = new EntityOperation("枚举控制属性","fieldRestrict","FieldRecord/fieldRestrictedList.do","glyphicon glyphicon-sort",OperationEnum.showColumn.name(),new EntityRecord(0));
                optionList.add(radioField);
            }
            //如果是单多选类型字段
            if (fieldName.indexOf("_mutibox") != -1) {
                if (map.get("share_field_id") == null){
                    EntityOperation radioField = new EntityOperation("枚举:下拉框(多)","addSinglebox","FieldRecord/fieldSelectBoxlist.do","glyphicon glyphicon-stats",OperationEnum.showColumn.name(),new EntityRecord(0));
                    optionList.add(radioField);
                }
            }
            Object chineObj = map.get("inchinese");
            Object idObj = map.get("id");
            Map<String,Object> dataMap = new HashMap<String,Object>();
            dataMap.put("id", idObj);
            dataMap.put("position", map.get("position"));
            dataMap.put("operation",optionList);
            dataMap.put("name", map.get("name"));
            dataMap.put("inchinese", chineObj);
            dataMap.put("field_type", fieldTypeStr);
            dataMap.put("calfield", "true".equals(map.get("calfield").toString()) ? "是" : "否");
            if (map.get("enum_share") != null) {
                String htmlspan = "<span style='color:blue' nodeid='" + map.get("share_field_id") + "'>" + map.get("enum_share") + "</span>";
                dataMap.put("enum_share", htmlspan);
            }

            String resText = "";
            if (map.get("restricter") != null) {
                Integer resId = (Integer) map.get("restricter");
                if (fInfoMap.keySet().contains(resId)) {
                    FieldRecord refField = (FieldRecord) fInfoMap.get(resId);
                    if (map.get("share_field_id") != null){
                        resText = "<span nodeid='" + map.get("restricter") + "' nodename='" + refField.getName() + "'"
                                + " childid='" + idObj + "' childname='" + map.get("name") + "' childLocal='" + chineObj + "' >"
                                + refField.getInchinese() + "</span>";
                    }else {
                        resText = "<span onclick='restricterSet(this)' style='color:#2a5493;cursor:pointer;' nodeid='" + map.get("restricter")
                                + "' nodename='" + refField.getName() + "' " + " childid='" + idObj + "' childname='" + map.get("name")
                                + "' childLocal='" + chineObj + "' >" + refField.getInchinese() + "</span>";
                    }
                }
            }
            dataMap.put("restricter", resText);

            resultDatas.add(dataMap);
        }
        resultMap.put(Const.ROWS, resultDatas);
        resultMap.put(Const.TOTAL, totalCounts);

        return resultMap;
    }

    /**
     * 根据实体id查询当前实体所有注册字段的id、name(英文名)、inchinese(中文名)
     * @author              xiaogq
     * @param entityId     实体id
     * @return
     */
    public Map<Integer, FieldRecord> getFieldLocalInfo(Integer entityId) {
        Map<Integer,FieldRecord> fieldInfoMap = new HashMap<Integer,FieldRecord>();
        //根据实体id查询当前实体所有注册字段的id、name(英文名)、inchinese(中文名)
        List<FieldRecord> allFieldList = this.fieldRecordDao.getFieldRestrictedList(entityId);
        for (FieldRecord allFr : allFieldList) {
            fieldInfoMap.put(allFr.getId(), allFr);
        }
        return fieldInfoMap;
    }

    /**
     * 根据实体id查询该实体所有的字段(系统字段与自定义字段)
     * @author         xiaogq
     * @param entityId     实体id
     * @return
     */
    public List<FieldRecord> getAllFields(int entityId) {
        return fieldRecordDao.getAllFields(entityId);
    }

    /**
     * 保存实体字段排序方法
     * @author         xiaogq
     * @param sortIds    排序字段id
     * @return
     */
    public int fieldSortUpdate(String sortIds) {
        //保存实体字段排序方法
        return fieldRecordDao.fieldSortUpdate(sortIds);
    }

    /**
     * 如果新建的是单选、下拉、下拉多选类型的字段则查询字段注册表中所有的该类型字段信息
     * @author         xiaogq
     * @return
     */
    public List<FieldRecord> getAllBoxFields() {
        return this.fieldRecordDao.getAllBoxFields();
    }

    /**
     * 添加自定义字段时验证字段英文名是否重复
     * @author         xiaogq
     * @param fieldName       输入的字段英文名称
     * @param entityId        实体id
     * @param fieldTypeId    具体字段类型(1:数值、2:百分比、3:货币、4:字符串、5:电子邮件、6:网址、7:文本域、8:长文本区域、9:引用、10:电话、11:下拉框、12:下拉框(多选)、13:日期、14:日期时间、15:自动编号、16:复选框、17:单选框、18:图片，19：身份证号，20：银行卡号)
     * @return
     */
    public Map<String, Object> validateFieldName(String fieldName,Integer entityId, Integer fieldTypeId) {
        String name = fieldName;
        switch (fieldTypeId) {
            case 1:
                fieldName = name + "_decimal";
                break;
            case 2:
                fieldName = name + "_precent";
                break;
            case 3:
                fieldName = name + "_currency";
                break;
            case 5:
                fieldName = name + "_email";
                break;
            case 6:
                fieldName = name + "_web";
                break;
            case 7:
                fieldName = name + "_textarea";
                break;
            case 8:
                fieldName = name + "_textblock";
                break;
            case 10:
                fieldName = name + "_phone";
                break;
            case 11:
                fieldName = name + "_singlebox";
                break;
            case 12:
                fieldName = name + "_mutibox";
                break;
            case 13:
                fieldName = name + "_date";
                break;
            case 14:
                fieldName = name + "_datetime";
                break;
            case 15:
                fieldName = name + "_autosno";
                break;
            case 16:
                fieldName = name + "_bit";
                break;
            case 17:
                fieldName = name + "_radio";
                break;
            case 18:
                fieldName = name + "_img";
                break;
            case 19:
                fieldName = name + "_idcard";
                break;
            case 20:
                fieldName = name + "_bankcard";
                break;
            default:
                fieldName = name + "_varchar";
        }

        Map<String, Object> map = new HashMap<String, Object>();
        boolean b = this.fieldRecordDao.isFieldNameExist(entityId, fieldName);
        map.put("value", b);
        return map;
    }

    /**
     * 添加自定义字段方法
     * @author         xiaogq
     * @param fieldRecord    要添加的字段注册信息
     * @param selectBox      如果添加的是单选、下拉、下拉多选类型的字段所有的枚举值
     */
    public void addFieldRecord(FieldRecord fieldRecord, String[] selectBox){
        //获取新建自定义字段类型(1:数值、2:百分比、3:货币、4:字符串、5:电子邮件、6:网址、7:文本域、8:长文本区域、9:引用、10:电话、11:下拉框、12:下拉框(多选)、13:日期、14:日期时间、15:自动编号、16:复选框、17:单选框、18:图片,19:身份证号，20：银行卡号)
        int fieldTypeId = fieldRecord.getFieldTypeId();
        String fieldName = null;

        String name = fieldRecord.getName();
        switch (fieldTypeId) {
            case 1:
                fieldName = name + "_decimal";
                break;
            case 2:
                fieldName = name + "_precent";
                break;
            case 3:
                fieldName = name + "_currency";
                break;
            case 5:
                fieldName = name + "_email";
                fieldRecord.setLength(64);
                break;
            case 6:
                fieldName = name + "_web";
                fieldRecord.setLength(255);
                break;
            case 7:
                fieldName = name + "_textarea";
                fieldRecord.setLength(32000);
                break;
            case 8:
                fieldName = name + "_textblock";
                fieldRecord.setLength(80000);
                break;
            case 9:
                int index = getQuoteFieldSuffix(fieldRecord);
                fieldName = "pk_t_" + fieldRecord.getQuoteEntity().getTableCode() + "_" + index;
                fieldRecord.setSuffix(index);
                break;
            case 10:
                fieldName = name + "_phone";
                break;
            case 11:
                fieldName = name + "_singlebox";
                break;
            case 12:
                fieldName = name + "_mutibox";
                fieldRecord.setLength(255);
                break;
            case 13:
                fieldName = name + "_date";
                break;
            case 14:
                fieldName = name + "_datetime";
                break;
            case 15:
                fieldName = name + "_autosno";
                break;
            case 16:
                fieldName = name + "_bit";
                if (StringUtils.isEmpty(fieldRecord.getDefaultValue())) {
                    fieldRecord.setDefaultValue("0");
                }
                break;
            case 17:
                fieldName = name + "_radio";
                fieldRecord.setLength(255);
                break;
            case 18:
                fieldName = name + "_img";
                fieldRecord.setLength(255);
                break;
            case 19:
                fieldName = name + "_idcard";
                break;
            case 20:
                fieldName = name + "_bankcard";
                break;
            default:
                fieldName = name + "_varchar";
        }

        fieldRecord.setName(fieldName);
        fieldRecord.setColomuDefines(null);
        //添加表结构字段以及外键关系、注册表中添加字段信息
        dbStructureDao.addField(fieldRecord);
    }

    /**
     * 根据字段名返回字段类型
     * @author         xiaogq
     * @param fieldName
     * @return
     */
    public int getFieldType(String fieldName) {
        //数值
        if (fieldName.endsWith("_decimal"))
            return 1;
        //百分比
        if (fieldName.endsWith("_precent"))
            return 2;
        //货币
        if (fieldName.endsWith("_currency"))
            return 3;
        //电子邮件类型
        if (fieldName.endsWith("_email"))
            return 5;
        //web网站
        if (fieldName.endsWith("_web"))
            return 6;
        //文本域类型字段
        if (fieldName.endsWith("_textarea"))
            return 7;
        //长文本域类型字段
        if (fieldName.endsWith("_textblock"))
            return 8;
        //引用
        if (fieldName.startsWith("pk_"))
            return 9;
        //电话号码
        if (fieldName.endsWith("_phone"))
            return 10;
        //下拉
        if (fieldName.endsWith("_singlebox"))
            return 11;
        //下来多选
        if (fieldName.endsWith("_mutibox"))
            return 12;
        //日期类型字段
        if (fieldName.endsWith("_date"))
            return 13;
        //日期时间类型字段
        if (fieldName.endsWith("_datetime"))
            return 14;
        //自动编号类型字段
        if (fieldName.endsWith("_autosno"))
            return 15;
        //布尔类型
        if (fieldName.endsWith("_bit"))
            return 16;
        //单选
        if (fieldName.endsWith("_radio"))
            return 17;
        //图片
        if (fieldName.endsWith("_img"))
            return 18;
        //身份证号
        if (fieldName.endsWith("_idcard"))
            return 19;
        //银行卡号
        if (fieldName.endsWith("_bankcard"))
            return 20;
        //如果是字符串
        return 4;
    }

    /**
     * 如果新建的是引用类型的字段根据主实体id与被引用实体id获取注册字段表中的字段id及英文名称
     * @author                  xiaogq
     * @param fieldRecord     字段对象
     * @return
     */
    private int getQuoteFieldSuffix(FieldRecord fieldRecord) {
        //如果新建的是引用类型的字段根据主实体id与被引用实体id获取注册字段表中的字段id及英文名称
        List<FieldRecord> frList = fieldRecordDao.getFieldsWitchQuoteEntity(fieldRecord.getEntityRecord().getTableCode(), fieldRecord.getQuoteEntity().getTableCode());
        List<String> alreayExistIndex = new ArrayList<String>();
        if(frList != null && frList.size() > 0){
            for (FieldRecord fr : frList) {
                alreayExistIndex.add(StringUtils.substringAfterLast(fr.getName(), "_"));
            }
        }else{
            alreayExistIndex.add("0");
        }
        int index = Integer.parseInt(alreayExistIndex.get(alreayExistIndex.size()-1)) + 1;
        return index;
    }

    /**
     * 根据字段Id查询注册字段所有信息
     * @author                  xiaogq
     * @param fieldId    注册字段Id
     * @return
     */
    public FieldRecord getFieldRecord(int fieldId) {
        FieldRecord field = fieldRecordDao.getFieldRecord(fieldId);
        return field;
    }

    /**
     * 修改字段信息
     * @author                  xiaogq
     * @param fieldRecord     字段信息对象
     */
    public Map<String, Object> updateFieldRecord(FieldRecord fieldRecord) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //修改字段信息
        int counts = fieldRecordDao.updateFieldRecord(fieldRecord);
        if(counts > 0){
            resultMap.put("results","sucess");
            fieldRecordDao.updateFieldColumnStruct(fieldRecord);
        }else{
            resultMap.put("results","error");
        }
        return resultMap;
    }

    /**
     * 查询当前库中实体表字段是否存在
     * @author                     xiaogq
     * @param      tableCode     实体id
     * @param      fieldName     注册字段英文名
     */
    public boolean checkedFieldIsExist(String fieldName, int tableCode) {
        return fieldRecordDao.checkedFieldIsExist(fieldName, tableCode);
    }

    /**
     * 查询当前枚举字段值是否在实体表中被引用
     * @author                     xiaogq
     * @param      tableCode     实体id
     * @param      fieldName     注册字段英文名
     */
    public boolean checkedFieldHasData(String fieldName, int tableCode) {
        return fieldRecordDao.checkedFieldHasData(fieldName, tableCode);
    }

    /**
     * 根据注册字段id删除字段信息
     * @author                     xiaogq
     * @param fieldRecord
     */
    public void fieldRecordDelete(FieldRecord fieldRecord) {
        //删除该字段所关联的所有关系
        dbStructureDao.deleteField(fieldRecord);
    }

    /**
     * 根据实体id、字段id获取所有受权限控制的字段信息
     * @author                     xiaogq
     * @param entityId            实体id
     * @param fieldId             字段id
     */
    public List<FieldControled> getFieldControledList(Integer entityId, Integer fieldId) {
        //获取所有的系统角色
        List<Role> roleList = roleDao.queryRoleAll();

        Map<String, FieldControled> authList = this.fieldRecordDao.getFieldControledList(entityId,fieldId);

        List<FieldControled> list = new ArrayList<FieldControled>();
        for (Role role : roleList) {
            FieldControled fc = new FieldControled();
            if (authList.keySet().contains(role.getId())) {
                fc = (FieldControled) authList.get(role.getId());
            }
            fc.setRoleId(role.getId());
            fc.setRoleName(role.getName());
            list.add(fc);
        }

        return list;
    }

    /**
     * 字段级权限设置保存方法
     * @author               xiaogq
     * @param entityId     实体id
     * @param fieldId      字段id
     * @param fieldName    字段名称
     * @param authArr      角色字段权限参数
     * @return
     */
    public void saveFieldControled(Integer entityId, Integer fieldId,String fieldName, String[] authArr) {
        fieldRecordDao.saveFieldControled(entityId, fieldId, fieldName,authArr);
    }

    /**
     * 根据实体id查询下拉框类型字段信息并排除当前下来字段
     * @author               xiaogq
     * @param entityId      实体id
     * @param fieldId       注册字段id
     * @return
     */
    public List<FieldRecord> getFieldRestrictedList(Integer entityId,Integer fieldId) {
        //查询当前实体下拉框类型字段
        List<FieldRecord> selFieldList = fieldRecordDao.getFieldsByEntityId(entityId,fieldId);
        return selFieldList;
    }

    /**
     * 根据当前字段id获取受约束关系的字段id
     * @author               xiaogq
     * @param fieldId       当前字段id
     * @return
     */
    public Integer getFieldRestricter(Integer fieldId) {
        return fieldRecordDao.getFieldRestricter(fieldId);
    }

    /**
     * 枚举知道定义约束关系保存方法
     * @author                   xiaogq
     * @param entityId          实体id
     * @param fieldId           注册字段id
     * @param resFieldId        新约束关系字段id
     * @param pidresFieldId    原约束关系字段id
     * @return
     */
    public int saveFieldRestricted(Integer entityId, Integer fieldId,Integer resFieldId, Integer pidresFieldId) {
        return fieldRecordDao.saveFieldRestricted(fieldId, resFieldId,pidresFieldId);
    }

    /**
     * 查询枚举值定义约束关系列表数据
     * @author                   xiaogq
     * @param fieldId       被约束字段id
     * @param resFieldId    约束字段id
     * @return
     */
    public List<Map<String, Object>> queryRestrictFields(Integer fieldId,Integer resFieldId) {
        return fieldRecordDao.queryRestrictFields(fieldId, resFieldId);
    }

    /**
     * 根据字段id、枚举值id查询约束关系对于的枚举值
     * @author                   xiaogq
     * @param fieldId           字段id
     * @param resOptionId       枚举值id
     * @return
     */
    public List<SelectBox> getRestrictShowFields(Integer fieldId, Integer resOptionId) {
        return fieldRecordDao.getRestrictShowFields(fieldId, resOptionId);
    }

    /**
     * 保存(编辑)属性级控制
     * @author                  xiaogq
     * @param fieldId          被约束字段id
     * @param list              约束关系集合信息
     * @param resOptionId      枚举值id
     * @param resOptionName    枚举值名称
     * @return
     */
    public int setRestrictShowFields(Integer fieldId, List<SelectBox> list,Integer resFieldId, Integer resOptionId, String resOptionName) {
        return fieldRecordDao.setRestrictShowFields(fieldId, list, resFieldId,resOptionId, resOptionName);
    }

}
